package com.ucvisitors.ui;

import android.app.Activity;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;

import com.example.ucvisitors.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.ucvisitors.dao.BuildingDbDAO;

public class MainActivity extends Activity {
	
	private GoogleMap map;
	private String buildingName;
	private double lon;
	private double lat;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setUpMapIfNeeded();	
		Bundle extras = getIntent().getExtras();
		
		if (extras != null)
		{
			buildingName = extras.getString("name");
			lon = extras.getDouble("lon");
			lat = extras.getDouble("lat");
			
			LatLng latLng = new LatLng(lat, lon);
			
			map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
			
			map.animateCamera(CameraUpdateFactory.zoomTo(18));
			map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(buildingName));
			
		}
		
	}
	
	private void setUpMapIfNeeded() {
		if(map==null){
			map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
			if (map != null)
			{
				setUpMap();
			}
		}	
	}
	

	private void setUpMap() {
		map.setMyLocationEnabled(true);
		
		LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		
		Criteria criteria = new Criteria();
		
		String provider = locManager.getBestProvider(criteria, true);
		
		Location myLocation = locManager.getLastKnownLocation(provider);
		
		map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
		
		if (myLocation != null){
		double latitude = myLocation.getLatitude();
		
		double longitude = myLocation.getLongitude();
		
		LatLng latLng = new LatLng(latitude, longitude);
		
		map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
		
		map.animateCamera(CameraUpdateFactory.zoomTo(18));
		map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here."));
		}
	}

	public void onClick_Destination(View v){	
		Intent intent = new Intent(MainActivity.this, SearchScreen.class);
    	startActivity(intent);
    	this.finish();
	}
	
}